package com.hj.aiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

/**
 * @author: hj
 * @description: 打印 info 级别日志、只输出单次用户提示词和 AI 回复的文本
 * @date: 2025/7/1 10:05
 */
@Slf4j
@Component
public class LoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    public AdvisedRequest beforeCall(AdvisedRequest advisedRequest) {
        log.info("请求参数：{}", advisedRequest.userText());
        return advisedRequest;
    }

    public AdvisedResponse afterCall(AdvisedResponse advisedResponse) {
        log.info("响应结果：{}", advisedResponse.response().getResult().getOutput().getText());
        return advisedResponse;
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        advisedRequest = beforeCall(advisedRequest);
        AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);

        return afterCall(advisedResponse);
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        advisedRequest = beforeCall(advisedRequest);
        Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);
        return new MessageAggregator().aggregateAdvisedResponse(advisedResponses, this::afterCall);

    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
